package shuangzu.top.zzurla.activities;

import android.app.Activity;
import android.app.Fragment;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.drawable.Animatable;
import android.os.Bundle;
import android.os.Handler;
import android.preference.PreferenceManager;
import android.support.v4.content.ContextCompat;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.Animation;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import okhttp3.*;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import shuangzu.top.zzurla.R;
import shuangzu.top.zzurla.adapters.bulletin_adapter;
import shuangzu.top.zzurla.entities.entity_bulletin;
import shuangzu.top.zzurla.utils.utils_jsonstring;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;

public class bulletin_fragment extends Fragment implements AdapterView.OnItemClickListener
        //implements AdapterView.OnItemClickListener
{

    private List<entity_bulletin> noticeinfo_list=new ArrayList<entity_bulletin>();
    private Handler handler=null;
    private String getjson_string="";
    private bulletin_adapter adapter=null;
    private ListView listView;
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View view=inflater.inflate(R.layout.bulletin_fragment,container,false);

        return view;
    }

    @Override
    public void onAttach(Activity activity) {

        super.onAttach(activity);


    }

    @Override
    public void onStart()
    {
        super.onStart();
        init_noticeinfo();
        adapter.notifyDataSetChanged();

    }

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        adapter=new bulletin_adapter(getActivity(),R.layout.bulletin_item,noticeinfo_list);
        listView =(ListView) getActivity().findViewById(R.id.view_markdownlist);
        listView.setOnItemClickListener((AdapterView.OnItemClickListener) this);
        listView.setAdapter(adapter);

    }

    @Override
    public void onResume() {

        super.onResume();
    }

    private void init_noticeinfo()
    {
        noticeinfo_list.clear();
        entity_bulletin ni1=new entity_bulletin(1, "公告１", "20160520126", "2018-11-1", "双足实验室","", "");
        //noticeinfo_list.add(ni1);
        entity_bulletin ni2=new entity_bulletin(2, "公告2", "20160520126", "2018-11-2", "双足实验室","", "");
        //noticeinfo_list.add(ni2);
        SharedPreferences pref;
        pref= PreferenceManager.getDefaultSharedPreferences(getActivity());
        String labid=pref.getString("lab_id","1");
        OkHttpClient okHttpClient=new OkHttpClient.Builder()
                .connectTimeout(10, TimeUnit.SECONDS)
                .writeTimeout(10,TimeUnit.SECONDS)
                .readTimeout(10,TimeUnit.SECONDS)
                .build();
        final Request request = new Request.Builder()
                .url("http://server.aspi.tech:8080/zrla/bulletin/findwithlimit?offsetNum=0&size=10")//请求的url
                .get()//设置请求方式，get()/post()  查看Builder()方法知，在构建时默认设置请求方式为GET
                .build(); //构建一个请求Request对象995547
        Call call = okHttpClient.newCall(request);
        call.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                System.out.println("连接失败");
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                if(response.code()==200) {
                    //System.out.println(response.body().string());
                    System.out.println("链接成功！");
                    getjson_string=response.body().string();
                    utils_jsonstring uj=new utils_jsonstring();
                    //handler=new Handler();
                    //handler.post(add_list_bulletinitem);
                    JSONArray jsonArray = null;
                    try {
                        jsonArray = new JSONArray(getjson_string);
                        System.out.println("let" + getjson_string +"\n + length:" + jsonArray.length());
                        for (int i = 0; i < jsonArray.length(); i++) {
                            //循环遍历，依次取出JSONObject对象
                            //用getInt和getString方法取出对应键值
                            JSONObject jsonObject = jsonArray.getJSONObject(i);
                            //eblist.add(new entity_bulletin(jsonObject.getInt("bull_id"),jsonObject.getString("bull_title"),jsonObject.getString("bull_pubulisher_id"),jsonObject.getString("bull_published_date"),jsonObject.getString("bull_tags"),jsonObject.getString("bulll_img"),jsonObject.getString("bull_markdown_path")));
                            noticeinfo_list.add(new entity_bulletin(jsonObject.getInt("bull_id"), jsonObject.getString("bull_title"), jsonObject.getString("bull_publisher_id"), jsonObject.getString("bull_published_date"), jsonObject.getString("bull_tags"), jsonObject.getString("bull_img"), jsonObject.getString("bull_markdown_path")));
                            //System.out.println(jsonObject.getInt("bull_id")+ jsonObject.getString("bull_title")+ jsonObject.getString("bull_publisher_id")+ uj.longToDate( jsonObject.getLong("bull_published_date"),"yyyy-MM-dd HH:mm:ss").toString()+ jsonObject.getString("bull_tags")+ jsonObject.getString("bull_img")+ jsonObject.getString("bull_markdown_path"));
                            System.out.println("添加成功！！");
                        }
                        adapter.notifyDataSetChanged();
                        //handler=new Handler();
                        //handler.post(add_list_bulletinitem);
                    }catch (Exception e)
                    {
                        System.out.println("添加失败！");
                    }

                }
            }
        });

    }

    Runnable add_list_bulletinitem=new Runnable() {
        @Override
        public void run() {

        }
    };

    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        //TextView txttitle=(TextView)view.findViewById(R.id.view_title);
        //txttitle.setText("Clicked" + position);
        TextView txttitle=(TextView)view.findViewById(R.id.view_title);
        TextView txtvalue=(TextView)view.findViewById(R.id.txtvalue);
        //Toast.makeText(getActivity(),"U clicked "+position+ " and title is " + txttitle.getText(),Toast.LENGTH_SHORT).show();
        Intent intent =new Intent(getActivity(),bulletin_markdown_view.class);
        intent.putExtra("value",txtvalue.getText());
        startActivity(intent);
    }
}
